/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package acscoreserver;

import acscoreserver.data.Game;
import acscoreserver.data.Log;
import acscoreserver.data.Gamefrag;
import java.io.IOException;
import java.util.Date;


import javax.persistence.Persistence;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author Ricardo
 */
public class ACScore {
    
    private javax.persistence.EntityManager entityManager1;

    /*private ProcessBuilder builder;
    private Map<String, String> environ;
    public Process process;
    private InputStream is;
    private InputStreamReader isr;
    private BufferedReader br;*/

    private SendMail sm;


    public ACScore(){

    }


    public void startACScore(ACServerProcess acServerProcess, String sendtoquecmd) throws IOException{


        /*

        builder = new ProcessBuilder(dir+commandfile);
        environ = builder.environment();
        builder.directory(new File(dir));

        

        
        process = builder.start();
        is = process.getInputStream();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);

        */

        
        String line;


        Log log=null;
        Game game=null;
        Gamefrag gamefrag=null;
        Date date=null;
        int gameId=0;

        

        String[] spresult;


       
        while ((line = acServerProcess.getBr().readLine()) != null) {

            EntityManagerFactory emf = Persistence.createEntityManagerFactory("acscoreserverPU");
            //EntityManager em = emf.createEntityManager();
            entityManager1= emf.createEntityManager();
            //entityManager1 = javax.persistence.Persistence.createEntityManagerFactory("acscoreserverPU").createEntityManager();
            

            if(line.compareTo("AssaultCube fatal error: could not crsaultCube fatal error: could not eate server info socket")==0){

                System.out.println("\n\nACScore.java:74:Exception:-----------"+line+"-----------------");
                //process.destroy();
                //System.exit(-1);
            }

            if(line.compareTo("")!=0){
                if(line.charAt(0)!='<' &&
                        line.compareTo("masterserver reply: ")!=0 &&
                        line.compareTo("sending request to localhost...")!=0
                ){


                    while(!entityManager1.isOpen()){
                        System.out.println("------------------- entityManager1 going to reloaded ");
                        //entityManager1 = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("acscoreserverPU").createEntityManager();
                        entityManager1=javax.persistence.Persistence.createEntityManagerFactory("acscoreserverPU").createEntityManager();
                        System.out.println("------------------- entityManager1 reloaded ");

                    }



                    date=new Date();

                    log= new Log();
                    log.setTimestamp(date);
                    log.setMsg(line);

                    entityManager1.getTransaction().begin();
                    entityManager1.persist(log);
                    entityManager1.merge(log);
                    entityManager1.getTransaction().commit();




                    //System.out.println("------------------- log id "+log.getId());

                    spresult=line.split(" ");
                    //System.out.println("linha::::"+line+ "   splitlenght:::" + spresult.length);


                    //[193.137.239.251] Barreiras fragged LP5
                    if(spresult.length==4){
                        if(spresult[2].compareTo("fragged")==0 && spresult[1].charAt(0)=='['){


                            game= entityManager1.find(game.getClass(),game.getId());

                            gamefrag= new Gamefrag();

                            gamefrag.setTimestamp(date);
                            gamefrag.setFragger(spresult[1]);
                            gamefrag.setFragged(spresult[3]);
                            gamefrag.setIdGame(game.getId());


                            entityManager1.getTransaction().begin();
                            entityManager1.persist(gamefrag);
                            entityManager1.merge(gamefrag);
                            entityManager1.getTransaction().commit();
                            
                        }
                    }




                    //Game start: deathmatch on ac_scaffold, 1 players, 8 minutes remaining, mastermode 0, (itemlist preloaded, 'getmap' not prepared)
                    if(spresult.length>10){
                        if(spresult[0].compareTo("Game")==0 && spresult[1].compareTo("start:")==0){

                            game= new Game();

                            game.setStarted(date);
                            game.setIdLogStarted(log.getId());

                            //spresult=line.split(" ");

                            int ion=2;
                            while(spresult[ion].compareTo("on")!=0){
                                ion++;
                            }
                            ion++;

                            game.setMap(spresult[ion].substring(0,spresult[ion].length()-1));

                            entityManager1.getTransaction().begin();
                            entityManager1.persist(game);
                            entityManager1.merge(game);
                            entityManager1.getTransaction().commit();
                            System.out.println("Game started");

                            //gameId=game.getId();
                        }
                    }

                    //Game status: deathmatch on ac_scaffold, game finished, open
                    if(spresult.length==8){
                        if(spresult[5].compareTo("game")==0 && spresult[6].compareTo("finished,")==0){


                            game= entityManager1.find(game.getClass(),game.getId());

                            game.setEnded(date);
                            game.setIdLogEnded(log.getId());

                            entityManager1.getTransaction().begin();
                            entityManager1.persist(game);
                            entityManager1.merge(game);
                            entityManager1.getTransaction().commit();


                            System.out.println("Game ended");
                        }
                    }

                    //[193.137.239.251] client connected
                    if(spresult.length==3){
                        if(spresult[1].compareTo("client")==0 && spresult[2].compareTo("connected")==0){



                            sm = new SendMail(sendtoquecmd);
                            sm.start();
                            

                            try {
                                sm.join();
                            } catch (InterruptedException ex) {
                                //Logger.getLogger(ACScore.class.getName()).log(Level.SEVERE, null, ex);
                                ex.printStackTrace();
                                System.out.println("\n\nACScore.java:178:InterruptedException: " + ex.getMessage());

                            }
                            catch (Exception ex) {
                                ex.printStackTrace();
                                System.out.println("\n\nACScore.java:181:Exception: " + ex.getMessage());

                            }finally{
                                System.out.println("----------emails sended--------------");

                            }

                        }
                    }


                }
            }//if(line.compareTo("")!=0){





            //entityManager1.clear();

            entityManager1.close();
            emf.close();

            





        }//while ((line = br.readLine()) != null) {
        System.out.println("\n\n--------------------Program terminated!---------------");



    }
}
